package com.maidada.mddaichat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maidada.mddaichat.common.BaseRequest;
import com.maidada.mddaichat.common.ErrorCode;
import com.maidada.mddaichat.common.ThrowUtils;
import com.maidada.mddaichat.constant.CommonConstant;
import com.maidada.mddaichat.constant.RoleConstant;
import com.maidada.mddaichat.dto.user.*;
import com.maidada.mddaichat.entity.User;
import com.maidada.mddaichat.exception.BusinessException;
import com.maidada.mddaichat.mapper.UserMapper;
import com.maidada.mddaichat.service.UserService;
import com.maidada.mddaichat.util.CommonUtils;
import com.maidada.mddaichat.util.JwtUtils;
import com.maidada.mddaichat.vo.user.UserDetailVO;
import com.maidada.mddaichat.vo.user.UserPageVO;
import com.maidada.mddaichat.vo.user.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

/**
 * [用户表]服务实现类
 *
 * @author wulinxuan
 * @date 2025-04-16 16:15
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;

    @Override
    public String register(UserRegisterRequest param) {
        // 查询用户
        User user = getOne(Wrappers.lambdaQuery(User.class).eq(User::getAccount, param.getAccount()));
        ThrowUtils.throwIf(Objects.nonNull(user), ErrorCode.DATA_ALREADY_EXISTS_ERROR, "用户已存在");

        // 保存用户
        User entity = new User();
        String encryptPassword = DigestUtils.md5DigestAsHex((param.getPassword() + CommonConstant.PASSWORD_SALT).getBytes());
        entity.setUsername(param.getUsername());
        entity.setAccount(param.getAccount());
        entity.setPassword(encryptPassword);
        entity.setRole(RoleConstant.USER_ROLE);
        save(entity);

        // 生成token
        return JwtUtils.generateToken(entity.getId());
    }

    @Override
    public String login(UserLoginRequest param) {
        // 查询用户
        User entity = getOne(Wrappers.lambdaQuery(User.class).eq(User::getAccount, param.getAccount()));
        ThrowUtils.throwIf(Objects.isNull(entity), ErrorCode.DATA_NOT_FOUND_ERROR, "用户不存在");

        // 验证密码
        String encryptPassword = DigestUtils.md5DigestAsHex((param.getPassword() + CommonConstant.PASSWORD_SALT).getBytes());
        ThrowUtils.throwIf(!entity.getPassword().equals(encryptPassword), ErrorCode.PARAMS_ERROR, "密码错误");

        // 生成token
        return JwtUtils.generateToken(entity.getId());
    }

    @Override
    public UserVO currentUser() {
        UserVO result = new UserVO();

        String userId = CommonUtils.getUserIdByRequest();

        User user = getById(userId);
        BeanUtils.copyProperties(user, result);

        return result;
    }

    @Override
    public void add(UserAddRequest param) {
        User entity = new User();

        // 字段填充
        BeanUtils.copyProperties(param, entity);

        save(entity);
    }

    @Override
    public void delete(BaseRequest param) {
        removeById(param.getId());
    }

    @Override
    public void update(UserUpdateRequest param) {
        User entity = getById(param.getId());
        if (Objects.isNull(entity)) {
            throw new RuntimeException("数据不存在");
        }

        // 字段填充
        BeanUtils.copyProperties(param, entity);

        updateById(entity);
    }

    @Override
    public UserDetailVO queryDetail(BaseRequest param) {
        UserDetailVO result = new UserDetailVO();

        User entity = getById(param.getId());
        if (Objects.isNull(entity)) {
            throw new RuntimeException("该数据不存在");
        }

        // 字段填充
        BeanUtils.copyProperties(entity, result);

        return result;
    }

    @Override
    public IPage<UserPageVO> queryPage(UserPageRequest param) {
        IPage<User> page = new Page<>(param.getPageNo(), param.getPageSize());

        // 查询条件
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();

        // 查询数据并转换
        IPage<User> pageResult = page(page, wrapper);
        return pageResult.convert(item -> {
            UserPageVO vo = new UserPageVO();
            BeanUtils.copyProperties(item, vo);
            return vo;
        });
    }
}
